package com.tian.controller;


import com.tian.pojo.User;
import com.tian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/userList")
    public String allUser(ModelMap modelMap) {
        List<User> users = userService.allUser();
        modelMap.put("users", users);
        return "userList";
    }

    @GetMapping("/add")
    public String toAddUser() {
        return "user-add";
    }

    @PostMapping("/add")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/user/userList";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userService.deleteUser(id);
        return "redirect:/user/userList";
    }

    @GetMapping("/update/{id}")
    public String toUpdataUser(@PathVariable("id") int id, Model model) {
        User user = userService.serachById(id);
        model.addAttribute("update", user);
        return "user-update";
    }

    @PostMapping("/update")
    public String updataUser(User user) {
        userService.updateUser(user);
        return "redirect:/user/userList";
    }

    @PostMapping("/search")
    public String searchName(User user,ModelMap modelMap) {
        List<User> users = userService.searchName(user);
        modelMap.put("users", users);
        return "userList";
    }
}